/**
 * Component of water level sensor.
 * It uses a megnetometer that operates similarly to a potentiometer to determine height of water column.
 * The resistance of the hardware sensor changes with position of a magnet in the nearby which is floating
 * on the water surface. Thus the input voltage on ADC refers linearly to position of magnet that means
 * height of water column in the tank.
 *
 * @author Paweł Pawłowski <abdul-pablo@tlen.pl>
 * @author Leily Zafari
 */


#include "tank.h"

module WaterLevelSensorM{
	provides {
		interface Read<double>;
	}
	uses {
		interface SBoard;
	}
}
implementation{

	double waterLevelValue;
	double sensorValue;
	double vref = TANK_SENSOR_VREF_VALUE;
	error_t sensorResult;

	/**
	 * It processes data read from A/D converter and transforms it into height of water column in the tank.
	 * It produces a signal Read.readDone with sensor result and water column height as parameters.
	 *
	 * @return void
	 */
	task void readDoneTask()
	{
		//TODO: acquire reference voltage value if it is actually involved into max voltage on adc

		//sensor data processing
		//sensor value scales linearly into height of water column
		waterLevelValue = (sensorValue/vref)*TANK_SENSOR_HEIGHT; //)+TANK_SENSOR_OFFSET;
		signal Read.readDone(sensorResult, waterLevelValue*1000);
	}

	/**
	 * @brief Command that reads data from ADC.
	 * @details It calls SBoard.readChannel(2). Then the component waits for the data from ADC.
	 *
	 * @return error_t Returns execution status.
	 */
	command error_t Read.read(){
		//return call ReadCapacitance.read();
		call SBoard.readChannel2();
		return SUCCESS;
	}

	/**
	 * @brief Event triggered when a data is acquired from ADC of SBoard.
	 * @details It saves obtained data and posts readDoneTask()
	 *
	 * @see readDoneTask
	 * @param channel uint8_t Number of channel read by ADC.
	 * @param value double Value return by the SBoard as A/D conversion result.
	 * @return void
	 */
	async event void SBoard.readDoneADC(uint8_t channel, double value){
		if(channel == 2) {
			sensorResult = SUCCESS;
			sensorValue = value;
			post readDoneTask();
		}
	}

	/**
	 * @brief Event triggered when data is acquired form SBoard I/O port.
	 * @param value uint8_t Value read by the SBoard.
	 * @return void
	 */
	async event void SBoard.readDoneIO(uint8_t value){

	}


}